package cn.gary.oaserver.config.security;

import cn.gary.oaserver.entity.TMenu;
import cn.gary.oaserver.entity.TRole;
import cn.gary.oaserver.service.ITMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import java.util.Collection;
import java.util.List;

/**
 * @Author: 邓必宏
 * @title:
 * @Demo:
 * @DateTime: 2024/4/8
 */

@Component
public class CustomFilter implements FilterInvocationSecurityMetadataSource {

    @Autowired
    ITMenuService menuService;

    AntPathMatcher antPathMatcher = new AntPathMatcher ( );

    @Override
    public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException {
        // 1、获取请求的url
        String requestUrl = ((FilterInvocation) o).getRequestUrl ( );
        // 2、获取菜单列表及每个菜单被授予的角色列表
        System.out.println ("请求路径"+requestUrl );
        List<TMenu> menusWithRole = menuService.getMenusWithRole ( );
        for (TMenu tMenu : menusWithRole) {
            //判断请求的url是否有权限
            if (antPathMatcher.match ( tMenu.getUrl ( ), requestUrl )) {
                String[] strings = tMenu.getRoles ( ).stream ( ).map ( TRole::getName ).toArray ( String[]::new );
                System.out.println ("可以请求的角色：" );
                for (String string : strings) {
                    System.out.print (string+"、" );
                }
                return org.springframework.security.access.SecurityConfig.createList ( strings );
            }
        }
        //否则默认有登录的权限
        return org.springframework.security.access.SecurityConfig.createList ( "ROLE_LOGIN" );
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return false;
    }
}
